package com.cngphone.AnFetion;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.net.Uri;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Contacts;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.cngphone.AnFetion.tools.LogUtil;
import com.cngphone.AnFetion2.AnFetion;
import com.cngphone.AnFetion2.R;

public final class MiscUtil {
    public static final int DIS_CONNECT_NOTIFY_ID = 0x782a;

    public static final ColorFilter COLORFILTER_GRAWSCALE;
    public static final ColorFilter COLORFILTER_NORMAL;
    static {
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        COLORFILTER_GRAWSCALE = new ColorMatrixColorFilter(cm);
        cm.setSaturation(1);
        COLORFILTER_NORMAL = new ColorMatrixColorFilter(cm);
    }

    private static Context appContext = null;
    private static NotificationManager nManger = null;

    public static AlertDialog getInviteDialog(final FetionListFriends ctx) {
        return getInviteDialog(ctx, null);
    }

    public static AlertDialog getInviteDialog(final FetionListFriends ctx, final FetionFriend friend) {
        final View view = LayoutInflater.from(ctx).inflate(R.layout.invite, null);
        FetionFriend f = ctx.mBoundService.getMyself();
        final EditText edit_nick = (EditText) view.findViewById(R.id.nickname);
        view.findViewById(R.id.import_contacts).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent i = new Intent(Intent.ACTION_PICK);
                i.setData(Uri.parse("content://contacts/phones"));
                ctx.startActivityForResult(i, FetionListFriends.IMPORT_PHONE_REQUEST_ID);
            }

        });
        if (friend != null) {
            view.findViewById(R.id.import_contacts).setVisibility(View.INVISIBLE);
            view.findViewById(R.id.mobileNo).setVisibility(View.INVISIBLE);
        }
        edit_nick.setText(f.getNickName());
        AlertDialog dialog = new AlertDialog.Builder(ctx).setTitle("添加好友").setView(view).setPositiveButton(
                "确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!MiscUtil.checkIsOnline()) return;

                        new Handler().post(new Runnable() {
                            @Override
                            public void run() {
                                String mobile = ((EditText) view.findViewById(R.id.mobileNo)).getText()
                                        .toString();
                                String nick = edit_nick.getText().toString();
                                ArrayList<FetionFriend> buddies = getBuddies();
                                FetionFriend ff = null;
                                if (friend != null && friend.type == Settings.TYPE_REFUSE) {
                                    ff = friend;
                                } else {
                                    if (mobile == null || mobile.length() < 11) {
                                        MiscUtil.notifyInviteFail(ctx);
                                        return;
                                    }
                                    ff = getFriendByMobile(mobile, buddies);
                                    if (ff != null) {
                                        MiscUtil.notifyInviteFail(ctx);
                                        return;
                                    }
                                    ff = new FetionFriend();
                                    ff.mobile_no = mobile;
                                    ff.Uri = "tel:" + mobile;
                                    ff.type = Settings.TYPE_NOT_FRIEND;
                                    ff.isMe = false;
                                    buddies.add(ff);
                                }

                                int ret = ctx.mBoundService.sendInvite(ff, nick);
                                if (ret == 0) {
                                    buddies.remove(ff);
                                    MiscUtil.notifyInviteFail(ctx);
                                } else {
                                    if (ret == 1) {
                                        ctx.mBoundService.getFriendInfo(ff);
                                    }
                                    MiscUtil.notifyFriendChange(ctx);
                                }
                            }
                        });
                    }

                }).setNegativeButton("取消", null).create();
        return dialog;
    }

    public static ArrayList<FetionFriend> getBuddies() {
        FetionService service = FetionService.getService();
        if (service == null || !FetionService.isLogined()) {
            return null;
        }
        return service.getFriendManager().getBuddies();
    }

    public static AlertDialog getSetStautsMenu(final FetionListFriends ctx, final FetionFriend friend) {
        int sel = 0, size = Settings.STATUS_MENU_IDS.length;
        for (; sel < size; sel++) {
            if (friend.getOnlineStatusInt() == Settings.STATUS_MENU_IDS[sel]) {
                break;
            }
        }
        return new AlertDialog.Builder(ctx).setTitle("更改在线状态").setSingleChoiceItems(Settings.STATUS_MENU,
                sel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!MiscUtil.checkIsOnline()) return;

                        final int newstatus = Settings.STATUS_MENU_IDS[which];
                        if (friend.getOnlineStatusInt() != newstatus) {
                            ctx.runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    if (ctx.mBoundService.setPresence(newstatus)) {
                                        friend.setOnlineStatus(newstatus);
                                        ctx.refreshSelf();
                                        // MiscUtil.notifyReceival(ctx);
                                    }
                                }

                            });
                        }
                        dialog.dismiss();
                    }

                }).create();
    }

    public static void notifyReceival(Context ctx) {
        Intent in = new Intent(Settings.ACTION_RECEIVE_MESSAGE);
        getContext(ctx).sendBroadcast(in);
    }

    public static void notifyInviteFail(Context ctx) {
        Intent in = new Intent(Settings.ACTION_SENT_INVITE_FAIL);
        getContext(ctx).sendBroadcast(in);
    }

    public static AlertDialog getReconnectDialog(final FetionListFriends ctx) {
        AlertDialog dialog = new AlertDialog.Builder(ctx).create();
        dialog.setTitle("系统提示");
        dialog.setMessage("与服务器断开连接！");
        dialog.setButton("返回登陆框", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ctx.isClosing = true;
                ctx.mBoundService.close();
                Intent intent = new Intent(ctx.getApplicationContext(), FetionLoginActivity.class);
                ctx.startActivity(intent);
                ctx.finish();
            }
        });
        dialog.setButton2("退出程序", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ctx.isClosing = true;
                ctx.mBoundService.close();
                // releaseAll();
                getContext(ctx).stopService(MiscUtil.getFetionServiceIntent(ctx));
                ctx.finish();
            }
        });
        return dialog;
    }

    public static Intent getFetionServiceIntent(Context ctx) {
        return new Intent(getContext(ctx), FetionService.class);
    }

    public static void notifyFriendChange(Context ctx) {
        Intent in = new Intent(Settings.ACTION_FRIEND_CHANGE);
        getContext(ctx).sendBroadcast(in);
    }

    public static Intent getHome(Context ctx) {
        Intent intent = new Intent(getContext(ctx), FetionListFriends.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        return intent;
    }

    public static void notifyDisconnect(Context ctx, String message, boolean failed) {
        Notification info = new Notification(R.drawable.fetion, message, System.currentTimeMillis());
        if (failed) {
            info.defaults = Notification.DEFAULT_SOUND;
            Intent i = new Intent(getContext(ctx), AnFetion.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            PendingIntent appIntent = PendingIntent.getActivity(getContext(ctx), 0, i,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            info.setLatestEventInfo(getContext(ctx), message, "", appIntent);
        } else {
            Intent i = new Intent(Settings.ACTION_RECONNECT_CLEAR);
            PendingIntent appIntent = PendingIntent
                    .getBroadcast(ctx, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
            info.setLatestEventInfo(getContext(ctx), message, "", appIntent);
        }

        ((NotificationManager) getContext(ctx).getSystemService(Context.NOTIFICATION_SERVICE)).notify(
                DIS_CONNECT_NOTIFY_ID, info);
    }

    public static Context getContext(Context ctx) {
        if (appContext == null && ctx != null) {
            appContext = ctx.getApplicationContext();
        }
        return appContext;
    }

    public static boolean checkIsOnline() {
        if (Settings.DEBUG) LogUtil.d(Settings.TAG, "currentStatus is " + FetionService.isLogined());
        if (FetionService.isLogined()) {
            return true;
        }
        Toast.makeText(getContext(null), "飞信断线中, 禁止此操作!", Toast.LENGTH_SHORT).show();
        return false;
    }

    public static NotificationManager getNotificationManager(Context ctx) {
        if (nManger == null) {
            nManger = (NotificationManager) getContext(ctx).getSystemService(Context.NOTIFICATION_SERVICE);
        }
        return nManger;
    }

    public static void cancelNotification(Context ctx, int id) {
        if (id <= 0) return;
        getNotificationManager(ctx).cancel(id);
    }

    public static FetionFriend getFriendByMobile(String mobile, ArrayList<FetionFriend> buddies) {
        if (mobile == null || mobile.equals("") || buddies == null || buddies.isEmpty()) {
            return null;
        }
        int size = buddies.size();
        for (int i = 0; i < size; i++) {
            FetionFriend ff = buddies.get(i);
            if (mobile.equals(ff.mobile_no)) {
                return ff;
            }
        }
        return null;
    }

    public static int getFriendIcon(FetionFriend friend) {
    	if (friend == null)
    		return R.drawable.user_offline;
        int drawable = R.drawable.user_offline;
        switch (friend.getOnlineStatusInt()) {
            case Settings.STATUS_OFFLINE:
                drawable = R.drawable.user_offline;
                if (friend.IsMobileNo) {
                    drawable = R.drawable.mobilebuddy;
                }
                break;
            case Settings.STATUS_AWAY:
                drawable = R.drawable.user_away;
                break;
            case Settings.STATUS_HIDDEN:
                drawable = R.drawable.user_hidden;
                break;
            case Settings.STATUS_ONLINE:
                drawable = R.drawable.user_online;
                break;
            case Settings.STATUS_BUSY:
                drawable = R.drawable.user_busy;
                break;
        }
        return drawable;
    }

    public static String getMobile(Context ctx, Uri uri) {
        Cursor c = getContext(ctx).getContentResolver().query(uri, new String[] { Contacts.Phones.NUMBER },
                null, null, null);
        if (c != null && c.moveToNext()) {
            String mobile = c.getString(0);
            return mobile.replace("-", "");
        }
        return null;
    }

    public static String toMobile(String s) {
        if (s == null) return null;
        if (s.startsWith("+86")) {
            s = s.substring(3);
        }
        if (s.startsWith("1") && s.length() == 11) {
            return s;
        }
        return null;
    }
    
    public static void updateMessageNotify(Context context, FriendManager friendManager, FetionFriend lastFriend) {
        // ((FetionService)context).setlastReceivedMessage(sipc.body); //Tiger.
        // 保存消息，用于在send框显示
        SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(context);
        if (preference.getBoolean(FetionPreferenceActivity.NOTIFICATION_ENABLE, true)) {
        	HashSet<FetionFriend> notify_friends = friendManager.getNotifyFriends();
        	if (notify_friends.size() == 0)	{
        		MiscUtil.cancelNotification(context, Settings.FRIEND_NOTIFYCATION_ID);
        		return;
        	}
        	StringBuilder sb = new StringBuilder();
        	if (lastFriend != null) {
        		sb.append(lastFriend.getName());
        		sb.append(" : ");
        		sb.append(lastFriend.lastMessage);
        	}
        	String msg = sb.toString();
	        Notification info = new Notification(R.drawable.fetion, msg, System.currentTimeMillis());
	        String contentTitle;
	        String contentText;
        	if (notify_friends.size() == 1) {
        		contentTitle = lastFriend.getName();
        		contentText = lastFriend.lastMessage;
        	} else {
        		ArrayList<String> friend_names = new ArrayList<String>();
        		for (FetionFriend fetionFriend : notify_friends) {
					friend_names.add(fetionFriend.getName());
				}
        		contentTitle = TextUtils.join(",", friend_names);
        		contentText = msg;
        	}
        	if (lastFriend != null) {
		        String ringtone = preference.getString(FetionPreferenceActivity.NOTIFICATION_RINGTONE, null);
		        info.sound = TextUtils.isEmpty(ringtone) ? null : Uri.parse(ringtone);
		        if (preference.getBoolean(FetionPreferenceActivity.NOTIFICATION_VIBRATE, true))
		        	info.defaults = Notification.DEFAULT_VIBRATE; 
		        //info.sound = Uri.parse("android.resource://com.cngphone.AnFetion/" + R.raw.newmessage);
		        info.ledARGB = 0xff00ff00;
		        info.ledOnMS = 1000;
		        info.ledOffMS = 3000;
		        if (preference.getBoolean(FetionPreferenceActivity.NOTIFICATION_LED, true))
		        	info.flags |= Notification.FLAG_SHOW_LIGHTS;
        	}
	        Intent contentIntent = null;
	        if (notify_friends.size() == 1) {
		        contentIntent = MiscUtil.getSendSmsIntent(context, lastFriend);
	        } else {
	        	contentIntent = MiscUtil.getHome(context);
	        }
	        PendingIntent appIntent = PendingIntent.getActivity(context, 0, contentIntent,
	                PendingIntent.FLAG_ONE_SHOT);
	        info.setLatestEventInfo(context, contentTitle, contentText, appIntent);
	        MiscUtil.getNotificationManager(context).notify(Settings.FRIEND_NOTIFYCATION_ID, info);

        }
    }

	private static Intent getSendSmsIntent(Context context, FetionFriend friend) {
		Intent intent;
		intent = new Intent(context, SendSMSActivity.class);
		intent.putExtra("uri", friend.Uri);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
		return intent;
	}

    /**
     * Indicates whether the specified action can be used as an intent. This method queries the
     * package manager for installed packages that can respond to an intent with the specified
     * action. If no suitable package is found, this method returns false.
     * 
     * @param context The application's environment.
     * @param action The Intent action to check for availability.
     * 
     * @return True if an Intent with the specified action can be sent and responded to, false
     *         otherwise.
     */
    public static boolean isIntentAvailable(Context context, String action) {
        final PackageManager packageManager = context.getPackageManager();
        final Intent intent = new Intent(action);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

}
